package com.umeox.watch.audiobooks.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.moto.watch.themes.widget.TextView;
import com.umeox.watch.audiobooks.R;
import com.umeox.watch.audiobooks.adapter.GalleryLayoutManager;
import com.umeox.watch.audiobooks.adapter.HotStoriesAdapter;
import com.umeox.watch.audiobooks.adapter.ScaleTransformer;
import com.umeox.watch.audiobooks.db.AppDatabase;
import com.umeox.watch.audiobooks.db.RecommendStory;
import com.umeox.watch.audiobooks.db.RecommendStoryDao;
import com.umeox.watch.audiobooks.utils.StoryManager;
import com.umeox.watch.audiobooks.utils.StoryManagerKt;
import com.umeox.watch.audiobooks.utils.ThreadPoolExecutorUtils;
import com.umeox.watch.moto.apiclient.model.StoryDTO;
import com.umeox.watch.moto.dataservice.constants.Constants;
import com.umeox.watch.moto.dataservice.proxy.PushApiClientProxy;
import com.yc.music.model.AudioBean;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ThemeAppCompatActivity implements Runnable, HotStoriesAdapter.OnClickListener {

    private RecyclerView mAudioRv;
    private List<AudioBean> mAudiobooksList;
    private HotStoriesAdapter mHotStoriesAdapter;
    private ThreadPoolExecutorUtils threadPoolExecutorUtils;

    private UIHandler mHandler;

    private TextView mCurrentStoryTv;

    private boolean isFetched;

    private RecommendStoryDao recommendStoryDao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState != null) {
            isFetched = savedInstanceState.getBoolean("isFetched", false);
        }
        recommendStoryDao = AppDatabase.Companion.get().recommendStoryDao();
        mHandler = new UIHandler(this);
        mAudiobooksList = new ArrayList<>();
        mAudiobooksList.clear();
        threadPoolExecutorUtils = new ThreadPoolExecutorUtils();
        if (!isFetched) {
            isFetched = true;
            threadPoolExecutorUtils.execute(this);
        } else {
            showDbStories();
        }

        initView();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean("isFetched", isFetched);
    }

    private void initView() {
        mAudioRv = findViewById(R.id.rv);
        mCurrentStoryTv = findViewById(R.id.tv_story_name);
        mHotStoriesAdapter = new HotStoriesAdapter(this, R.layout.item_hot_story);
        mHotStoriesAdapter.setOnClickListener(this);
        mAudioRv.setAdapter(mHotStoriesAdapter);

        mAudioRv.setHasFixedSize(true);

        GalleryLayoutManager galleryLayoutManager = new GalleryLayoutManager(GalleryLayoutManager.HORIZONTAL);
        galleryLayoutManager.setItemTransformer(new ScaleTransformer());
        galleryLayoutManager.attach(mAudioRv);


        galleryLayoutManager.setOnItemSelectedListener((recyclerView, item, position) -> {
            mCurrentStoryTv.setText(mAudiobooksList.get(position).getTitle());
            setUnSelectedViewAlpha();
            item.setAlpha(1.0F);
        });

        findViewById(R.id.iv_list).setOnClickListener(v -> {
            startActivity(new Intent(MainActivity.this, AllStoryActivity.class));
        });
    }

    private void setUnSelectedViewAlpha() {
        int itemCount = mHotStoriesAdapter.getItemCount();
        for (int i = 0; i < itemCount; i++) {
            View itemView = mAudioRv.getChildAt(i);
            if (itemView != null) {
                itemView.setAlpha(0.6F);
            }
        }

    }


    @Override
    public void run() {
        getAudioData();
    }

    private void getAudioData() {
        //先拿本地的数据展示
        showDbStories();

        //刷新服务器最新的数据替换本地并保存
        try {
            List<StoryDTO> storyDTOList = PushApiClientProxy.fetchBinder().getRecommendStories();
            if (storyDTOList != null && !storyDTOList.isEmpty()) {
                Logger.e(storyDTOList.toString());
                recommendStoryDao.deleteAll();
                List<RecommendStory> recommendStories = new ArrayList<>();
                for (StoryDTO storyDTO : storyDTOList) {
                    RecommendStory recommendStory = new RecommendStory();
                    recommendStory.setId(storyDTO.id);
                    recommendStory.setName(storyDTO.name);
                    recommendStory.setCoverUrl(storyDTO.coverUrl);
                    recommendStory.setAuthor(storyDTO.author);
                    recommendStory.setStoryUrl(storyDTO.storyUrl);
                    recommendStory.setStoryLength(storyDTO.storyLength);
                    recommendStories.add(recommendStory);
                }
                recommendStoryDao.save(recommendStories);
                covert2AudioBeanList(recommendStories);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }


        //For test
        /*try {
            String storiesJsonStr = UtilKt.getDataFromJson("stories_data.json");
            JSONArray jsonArray = new JSONArray(storiesJsonStr);
            Logger.e("jsonArray=" + jsonArray);
            List<StoryBean> storyBeanList = GsonUtils.toList(jsonArray.toString(), StoryBean.class);
            if (storyBeanList != null) {
                for (StoryBean storyBean : storyBeanList) {
                    if (mAudiobooksList.size() == 7) {
                        break;
                    }
                    AudioBook audioBook = new AudioBook();
                    audioBook.setId(storyBean.getId());
                    audioBook.setName_ar(storyBean.getName_ar());
                    audioBook.setName_en(storyBean.getName_en());
                    audioBook.setImage_src(storyBean.getImage_src());
                    audioBook.setFile_src(storyBean.getFile_src());
                    mAudiobooksList.add(audioBook);
                }
                StoryManager.INSTANCE.getHotStoryList().clear();
                StoryManager.INSTANCE.getHotStoryList().addAll(mAudiobooksList);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            mHandler.obtainMessage(UIHandler.UPDATE_UI).sendToTarget();
        }*/
    }

    private void showDbStories() {
        List<RecommendStory> recommendStoryList = recommendStoryDao.loadAll();
        if (recommendStoryList != null) {
            covert2AudioBeanList(recommendStoryList);
        }
    }

    private void covert2AudioBeanList(List<RecommendStory> recommendStoryList) {
        if (recommendStoryList == null) {
            return;
        }
        mAudiobooksList.clear();
        for (RecommendStory recommendStory : recommendStoryList) {
            AudioBean audioBook = new AudioBean();
            audioBook.setId(String.valueOf(recommendStory.getId()));
            audioBook.setTitle(recommendStory.getName());
            audioBook.setArtist(recommendStory.getAuthor());
            audioBook.setCoverPath(recommendStory.getCoverUrl());
            audioBook.setPath(recommendStory.getStoryUrl());
            audioBook.setDuration(recommendStory.getStoryLength() * 1000L);
            mAudiobooksList.add(audioBook);
        }
        StoryManager.INSTANCE.getHotStoryList().clear();
        StoryManager.INSTANCE.getHotStoryList().addAll(mAudiobooksList);
        mHandler.obtainMessage(UIHandler.UPDATE_UI).sendToTarget();
    }

    @Override
    public void onPositionClick(int position) {
        Intent intent = new Intent(this, PlayingActivity.class);
        intent.putExtra(StoryManagerKt.INTENT_KEY_LIST_TYPE, StoryManagerKt.LIST_TYPE_HOT);
        intent.putExtra(StoryManagerKt.INTENT_KEY_AUDIO_ID, mAudiobooksList.get(position).getId());
        startActivity(intent);
    }


    private static class UIHandler extends Handler {

        public static final int GET_DATA = 0x10;
        public static final int UPDATE_UI = 0x11;
        private WeakReference<MainActivity> reference;

        public UIHandler(MainActivity activity) {
            reference = new WeakReference<>(activity);
        }


        @Override
        public void handleMessage(Message msg) {
            final MainActivity activity = reference.get();
            if (activity == null) {
                return;
            }

            switch (msg.what) {
                case GET_DATA:
                    activity.threadPoolExecutorUtils.execute(activity);
                    break;
                case UPDATE_UI:
                    activity.mHotStoriesAdapter.setAudioDatas(activity.mAudiobooksList);
                    break;
            }
        }
    }

    @SuppressLint("WrongConstant")
    @Override
    protected void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(Constants.ACTION_UPLOAD_STORY_PLAY_HISTORY);
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | Constants.FLAG_RECEIVER_INCLUDE_BACKGROUND);
        sendBroadcast(intent);
    }
}
